/*
 * pollerutils.c
 *
 *  Created on: Feb 10, 2012
 *      Author: daniel
 */

#include "pollerutils.h"
#include <curl/curl.h>
#include <string.h>
#include <stdlib.h>

static size_t curlcallback(void *contents, size_t size, size_t nmemb,
		void *userp) {
	size_t realsize = size * nmemb;
	expandinglump_t* mem = userp;

	mem->memory = realloc(mem->memory, mem->size + realsize + 1);
	if (mem->memory == NULL) {
		/* out of memory! */
		printf("not enough memory (realloc returned NULL)\n");
		//exit(EXIT_FAILURE);
	}

	memcpy(&(mem->memory[mem->size]), contents, realsize);
	mem->size += realsize;
	mem->memory[mem->size] = 0;

	return realsize;
}

CURLcode pollerutils_httpget(const char* url, expandinglump_t* chunk) {

	CURL *curl;
	curl = curl_easy_init();
	if (curl == NULL) {
		return -1;
	}

	chunk->memory = malloc(1); /* will be grown as needed by the realloc above */
	chunk->size = 0; /* no data at this point */

	CURLcode res;

	curl_easy_setopt(curl, CURLOPT_URL, url);
	/* send all data to this function  */
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlcallback);

	/* we pass our 'chunk' struct to the callback function */
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, chunk);

	curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5);

	res = curl_easy_perform(curl);

	/* always cleanup */
	curl_easy_cleanup(curl);

	return res;
}
